package com.wondersgroup.insurance.claimlib;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.wondersgroup.insurance.claimlib.base.BaseActivity;
import com.wondersgroup.insurance.claimlib.constant.ConstantStr;
import com.wondersgroup.insurance.claimlib.utils.NetManagerUtil;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/6.
 */

public class HomeActivity extends BaseActivity{
    private WebView webview;


    private String access_token;
    private String user_id;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_claim_home);
        initParams();
        initView();
        initListener();
        Map<String,String> extraHeaders = new HashMap<String, String>();
        extraHeaders.put("accessToken", access_token);
        extraHeaders.put("yxUserId", user_id);
        webview.loadUrl(ConstantStr.login,extraHeaders);
    }

    @Override
    public void initParams() {
        if (getIntent() !=null){
            access_token = getIntent().getStringExtra("access_token");
            user_id = getIntent().getStringExtra("user_id");
        }
        if (TextUtils.isEmpty(access_token) || TextUtils.isEmpty(user_id)){
            exitFunction(-1,"参数有误");
        }
        if (!NetManagerUtil.isConnectNet(getApplicationContext())){
            exitFunction(-2,"网络异常");
        }
    }

    @Override
    public void initView() {
        super.initView();
        webview = (WebView) findViewById(R.id.webview);
        webview.setHorizontalScrollBarEnabled(false);
        webview.setHorizontalScrollbarOverlay(false);
        webview.setVerticalScrollBarEnabled(false);
        webview.setVerticalScrollbarOverlay(false);
        WebSettings settings = webview.getSettings();


        CookieManager cookieManager = CookieManager.getInstance();
        String api = android.os.Build.VERSION.SDK;
        if (20 < Integer.valueOf(api)) {
//            cookieManager.setAcceptThirdPartyCookies(webview, true);
        } else {
            cookieManager.setAcceptCookie(true);
        }
        settings.setSupportZoom(false);//
        settings.setUseWideViewPort(false);
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(true);//
        settings.setBuiltInZoomControls(false);
        settings.setAppCacheEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);
        String cacheDir = getApplicationContext()
                .getDir("cache", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(cacheDir);
        settings.setAppCacheMaxSize(50 * 1024 * 1024);
        //
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        if (Build.VERSION.SDK_INT >= 19) {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http://") || url.startsWith("https://")) {

//                    if (url.indexOf(INDEX_ERR) != -1) {
//
//                    } else {
//                        if (url.contains(INDEX_MAIN)){
//                            tvTiteRight.setVisibility(View.VISIBLE);
//                        }else {
//                            tvTiteRight.setVisibility(View.GONE);
//
//                        }
                    Log.e("",url);

                    view.loadUrl(url);
//
//                    }
                } else {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                return true;
            }


            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); //
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });
        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onExceededDatabaseQuota(String url,
                                                String databaseIdentifier, long currentQuota,
                                                long estimatedSize, long totalUsedQuota,
                                                WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(estimatedSize * 2);
            }

            @Override
            public void onReachedMaxAppCacheSize(long spaceNeeded,
                                                 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(spaceNeeded * 2);
            }

            public void onProgressChanged(WebView view, int progress) {
//                if (!isShowing) {
//                    mHandler.sendEmptyMessage(2);
//                }
//                if (progress >= 85) {
//                    mHandler.sendEmptyMessage(3);
//                }
                super.onProgressChanged(view, progress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                Log.d("ANDROID_LAB", "TITLE=" + title);
//                if(title == null) title = "";
//                int pr = title.indexOf("?");
//                if(pr < 0)pr = 5;
//                if(title.length() > pr && view.getUrl().contains(title.substring(0,pr)))return;
//                tvTitle.setText(title);
            }
        });

//        webview.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK&& webViewGoBack()) {
//                    return true;
//                }
//                return false;
//            }
//        });

        webview.addJavascriptInterface(new JsUtil(), "goldbowl");

    }

    @Override
    public void initListener() {
    }

    @Override
    public void destoryRes() {
        super.destoryRes();
        if (webview != null){
            webview.clearCache(true);
            webview.destroy();
        }
    }



    private boolean webViewGoBack() {
        if (webview != null && webview.canGoBack()) {
            WebBackForwardList list = webview.copyBackForwardList();
            String backUrl = list.getItemAtIndex(list.getCurrentIndex() - 1).getUrl();

//            if (backUrl.contains("/html/jfw/nologin.html")) return false;
            webview.goBack();
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK&& event.getAction() == KeyEvent.ACTION_DOWN){

            return true;
        }else {
            return super.onKeyDown(keyCode, event);

        }
    }

    class JsUtil{
        @JavascriptInterface
        public void closePageD(){
            exitFunction(RETURN_CODE_OK,"");
        }
    }
}
